package com.newx.open.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Classname SignUtils
 * @Description TODO 加签验签工具类
 * @Date 2024/5/21 16:04
 * @Created by yxl
 */
@Data
public class NewxRequest {

    private static final Logger LOGGER = LoggerFactory.getLogger(NewxRequest.class);

    public static String signRequest(Map<String,Object> params,String secret){
        if(params.containsKey("sign")){
            params.remove("sign");
        }
        String[] keys = (String[]) params.keySet().toArray(new String[]{});
        Arrays.sort(keys);
        StringBuilder query = new StringBuilder();
        query.append(secret);
        String[] arr$ = keys;
        int len$ = keys.length;
        for(int i$ = 0; i$ < len$; ++i$) {
            String key = arr$[i$];
            String value = params.get(key).toString();
            if(!key.isEmpty() && !value.isEmpty()){
                query.append(key).append(value);
            }
        }
        query.append(secret);
        String md5 = SecureUtil.md5(query.toString());
        return md5.toUpperCase();
    }

    /**
     * 验签
     * @param request
     * @param sign
     * @param appSecret
     * @return
     */
    public static void verifyRequestParameter(HttpServletRequest request,String sign,String appSecret){
        String appId = request.getParameter("app_id");
        Map<String, Object> params = getParameterMap(request);
        params.put("app_id",appId);
        String signRequest = signRequest(params, appSecret);
        LOGGER.info("客户端传递的签名={},服务端生成的签名={},requestData={},app_id={}",
                sign,signRequest, JSONUtil.toJsonStr(request.getParameter("requestData")),appId);
        boolean equals = sign.equals(signRequest);
        System.out.println("equals="+equals);
        Assert.isTrue(sign.equals(signRequest),"签名验证失败");
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    public static Map<String,Object> getParameterMap(HttpServletRequest request){
        Map<String, String[]> properties = request.getParameterMap();
        Map<String,Object> returnMap = new HashMap<>();
        Iterator entries = properties.entrySet().iterator();
        String name = "";
        for (String value = "" ; entries.hasNext(); returnMap.put(name, value)){
            Map.Entry entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            } else if (!(valueObj instanceof String[])) {
                value = valueObj.toString();
            } else {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; ++i){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            }
        }
        return returnMap;
    }
}
